const { parse } = require("path")
const { writeFileSync } = require("fs")
const { resolve, traversingDir, getDirs, hump2short, short2Hump } = require("./module")

const rootDir = resolve("./components/")
const componentsEntrance = resolve("./components/index.js")
const componentsScssEntrance = resolve("./components/index.scss")
const componentsDTs = resolve("./components.d.ts")

function getIndexFile(pathArray) {
	return pathArray.find(item => item === "index.jsx" || item === "index.vue")
}

function generate() {
	const componentsElement = getDirs(traversingDir("./components"), rootDir)

	let importString = ""
	let useString = ""

	let scssImportString = ""

	let dTsImportString = ""
	let dTsString = ""

	componentsElement.map(item => {
		const componentFile = traversingDir(resolve(rootDir + "/" + item))

		const indexFile = getIndexFile(componentFile)
		const indexScss = componentFile.includes("index.scss")
		if (!indexFile) return

		const componentName = "V" + short2Hump(item)
		const componentKebabName = hump2short(item)
		const componentExtName = parse(indexFile).ext
		let componentPath = "./" + item
		if (componentExtName === ".vue") {
			componentPath += "/" + indexFile
		}

		importString += `import ${componentName} from "${componentPath}"\n`
		useString += `		app.component("v-${componentKebabName}", ${componentName})\n`

		if (indexScss) {
			scssImportString += `@import "./${item}/index.scss";\n`
		}

		dTsImportString += `import ${componentName} from "./components/${item}/index${componentExtName}"\n`
		dTsString += `		${componentName}: typeof ${componentName}\n`
	})

	writeFileSync(
		componentsEntrance,
		`${importString}
export default {
	install: (app) => {
${useString}	},
}
`,
		{ encoding: "utf-8" }
	)

	writeFileSync(componentsScssEntrance, scssImportString, { encoding: "utf-8" })
	writeFileSync(
		componentsDTs,
		`${dTsImportString}
declare module "vue" {
	export interface GlobalComponents {
${dTsString}	}
}

const install: (Vue: any) => void
export default {
	install,
}
`,
		{ encoding: "utf-8" }
	)
}

module.exports = function generateComponents() {
	return {
		name: "generateComponents",
		options() {
			console.log("开始生成组件!")
			generate()
			console.log("生成组件结束!")
		},
		buildStart() {
			console.log("开始生成组件!")
			generate()
			console.log("生成组件结束!")
		},
	}
}
